<template>
  <Topbar></Topbar>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field v-model="username" name="用户名" label="用户名" placeholder="用户名"
                 :rules="[{ required: true, message: '请填写用户名' }]"/>
    </van-cell-group>
    <van-cell-group inset>
      <!-- 单选 -->
      <van-field name="radio" label="单选框">
        <template #input>
          <van-radio-group v-model="sex" direction="horizontal">
            <van-radio name="1">男</van-radio>
            <van-radio name="2">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <!-- 图片上传 -->
      <van-field name="uploader" label="更改头像">
        <template #input>
          <van-uploader :after-read="afterRead" v-model="avatar" reupload max-count="1"/>
        </template>
      </van-field>
      <!-- 个性签名-->
      <!-- 可以使用 CellGroup 作为容器 -->
      <van-field
          v-model="individuality"
          rows="1"
          autosize
          label="留言"
          type="textarea"
          placeholder="请输入留言"
      />
    </van-cell-group>
    <!--            提交按钮-->
    <van-button type="primary" block class="btn-save" @click="saveClick">保存</van-button>
  </van-form>

</template>

<script setup lang="ts">
import {ref} from 'vue';
import Topbar from "../../components/Topbar.vue";
import {useRouter} from "vue-router";
import {useLoginStore} from "../../store/login";
import {UserInfo} from "../../type/user";
import {useUserStore} from "../../store/user";
import {UploaderFileListItem} from "vant";
import {UploaderAfterRead} from "vant/es/uploader/types";


// 用户名
const username = ref('');
const onSubmit = () => {
  console.log('submit');
};
// 单选按钮
const sex = ref('1');
// 头像上传
const avatar = ref([
  {url: ''},
]);

// 个性化签名
const individuality = ref("")

// 实例化路由
const router = useRouter()

// 实例化仓库
const loginStore = useLoginStore()

// 从获取到仓库中的值
loginStore.getUserInfo()


// 组件
loginStore.$subscribe((mutation, state) => {
  // console.log(state.user)
  const user = state.user as UserInfo
  username.value = user.name
  sex.value = String(user.sex)
  individuality.value = user.individuality
  avatar.value[0].url = `api/${user.avatar}`
})


const userStore = useUserStore()


//修改信息  保存按钮的回调函数
const saveClick = () => {
  userStore.editUserInfo(username.value, Number(sex.value), individuality.value)
}


// 上传图片
const afterRead = async (file: any) => {
  // 此时可以自行将文件上传至服务器
  // const url = await uploadStore.UploadImg(file.file as File)

  userStore.imgUserInfo(file.file as File)
};
</script>

<style scoped lang="less">
.btn-save {
  position: fixed;
  bottom: 0px;
}
</style>